package host.skiree.nettydemo.server.service.impl;

import host.skiree.nettydemo.message.LoginRequestMessage;
import host.skiree.nettydemo.message.LoginResponseMessage;
import host.skiree.nettydemo.message.Message;
import host.skiree.nettydemo.server.dto.UserChannel;
import host.skiree.nettydemo.server.dto.factory.UserChannelFactory;
import host.skiree.nettydemo.server.dto.impl.UserChannelImpl;
import host.skiree.nettydemo.server.service.MessageHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author anorak
 */
public class Login implements MessageHandler {

    private static final Map<String, String> AUTHOR_INFO = new HashMap<>();

    static {
        AUTHOR_INFO.put("zhangsan", "zhangsan");
        AUTHOR_INFO.put("lisi", "lisi");
        AUTHOR_INFO.put("wangwu", "wangwu");
    }

    @Override
    public void handleMessage(ChannelHandlerContext ctx, Message message) {
        LoginRequestMessage loginMessage = (LoginRequestMessage) message;
        if ( AUTHOR_INFO.keySet().contains(loginMessage.getUsername()) ){
            if ( AUTHOR_INFO.get(loginMessage.getUsername()).equals(loginMessage.getPassword()) ){
                if (UserChannelFactory.getInstance().getChannel(loginMessage.getUsername()) != null){
                    Channel channel = UserChannelFactory.getInstance().getChannel(loginMessage.getUsername());
                    channel.writeAndFlush(new LoginResponseMessage(false, "用户已在其他设备登录"));
                    UserChannelImpl.USER_CHANNEL_MAP.remove(channel);
                    channel.close();
                    UserChannelFactory.getInstance().bind(ctx.channel(), loginMessage.getUsername());
                    ctx.writeAndFlush(new LoginResponseMessage(true, "已移除上个用户,并成功登录"));
                }else {
                    UserChannelFactory.getInstance().bind(ctx.channel(), loginMessage.getUsername());
                    ctx.writeAndFlush(new LoginResponseMessage(true, "用户登录成功"));
                }
            }else {
                ctx.writeAndFlush(new LoginResponseMessage(false, "用户密码错误"));
            }
        }else {
            ctx.writeAndFlush(new LoginResponseMessage(false, "用户不存在"));
        }
    }

}
